# -*- coding:utf-8 -*-

# @Time : 2022/11/20 18:29
# @Author : 快乐的小猴子
# @Version : 
# @Function : 
import requests
from lxml import etree

if __name__ == '__main__':
    URL = 'https://www.dy2018.com'
    NUMS = {'1': [1, 1],
            '2': [1, 2],
            '3': [2, 1],
            '4': [2, 2],
            '5': [3, 1],
            '6': [3, 2],
            '7': [4, 1],
            '8': [4, 2],
            }
    INFOS = {
        '1': '2023新片精品',
        '2': '2023必看热片',
        '3': '迅雷电影资源',
        '4': '经典大片',
        '5': '华语电视剧',
        '6': '日韩电视剧',
        '7': '欧美电视剧',
        '8': '综艺&动漫',
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }

    def views():
        """提示信息展示"""
        for k, v in INFOS.items():
            print(k, v)


    def movie_hrefs(num):
        """爬取主页电影链接信息"""
        num1 = str(NUMS.get(num)[0])
        num2 = str(NUMS.get(num)[1])
        resp = requests.get(URL, headers=headers)
        resp.encoding = 'gbk'
        et = etree.HTML(resp.text)
        movie_href = et.xpath(
            '//div[@class="bd2"]/div[@class="index_list"][' + num1 + ']/div[@class="co_area2"][' + num2 + ']/div[@class="co_content222"]/ul/li/a/@href')
        if num == '1':
            del (movie_href[0])
        return movie_href


    def child_urls(num):
        """获取子页面的url地址"""
        urls_news = []
        rest = movie_hrefs(num)
        for i in range(0, len(rest)):
            child_url = URL + rest[i]
            urls_news.append(child_url)
        return urls_news


    def movie_details(num):
        """爬取子页面电影详情信息"""
        url_new = child_urls(num)
        list_infos = []
        for url in url_new:
            resp_new = requests.get(url, headers=headers)
            resp_new.encoding = 'gbk'
            et_child = etree.HTML(resp_new.text)
            movie_name = et_child.xpath('//div[@class="co_area2"]/div[@class="title_all"]//text()')[0]
            down_addr = et_child.xpath('//div[@id="downlist"]//a/@href')[0]
            list_infos.append((movie_name, down_addr,))
        return list_infos


    def save_file(num):
        """将爬取的电影详情信息保存到文件中"""
        file = open('./files/{}.xlsx'.format(INFOS[num]), 'w', encoding='utf-8')
        file.write("说明：请使用迅雷进行下载~~~\n")
        rests = movie_details(num)
        for x in range(0, len(rests)):
            file.write(str(x + 1) + '\t' + rests[x][0] + '\t' + rests[x][1] + '\n')
            print(str(x + 1) + '\t' + rests[x][0] + '\t' + rests[x][1] + '\t下载完成！！！')
        file.close()
        print("文件保存完成！！！")


    while True:
        views()
        num = input("请选择您要进行下载的电影类型所对应的序号(1-8),q/Q退出：").strip()
        if num.upper() == 'Q':
            break
        save_file(num)
